package notes.java.juc.demo;

// 启动三个线程为别为A B　C 分别交替打印ABC ABC ABC
public class K10_TestPrint {

	public static void main(String[] args) {

		Print print = new Print();
		new Thread(new PrintA(print), "线程A").start();
		new Thread(new PrintB(print), "线程B").start();
		new Thread(new PrintC(print), "线程C").start();
	}
}

class PrintA implements Runnable {
	private Print print;

	public PrintA(Print print) {
		super();
		this.print = print;
	}

	@Override
	public void run() {
		while (true) {
			try {
				print.toPrintA();
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}
}

class PrintB implements Runnable {
	private Print print;

	public PrintB(Print print) {
		super();
		this.print = print;
	}

	@Override
	public void run() {
		while (true) {
			try {
				print.toPrintB();
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}
}

class PrintC implements Runnable {
	private Print print;

	public PrintC(Print print) {
		super();
		this.print = print;
	}

	@Override
	public void run() {
		while (true) {
			try {
				print.toPrintC();
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}
}

class Print {

	private String flag = "A";

	public synchronized void toPrintA() throws InterruptedException {
		if (flag.equals("A")) {
			System.out.println(Thread.currentThread().getName() + ":" + flag);
			flag = "B";
			super.notifyAll();
		} else {
			super.wait();
		}
	}

	public synchronized void toPrintB() throws InterruptedException {
		if (flag.equals("B")) {
			System.out.println(Thread.currentThread().getName() + ":" + flag);
			flag = "C";
			super.notifyAll();
		} else {
			super.wait();
		}
	}

	public synchronized void toPrintC() throws InterruptedException {
		if (flag.equals("C")) {
			System.out.println(Thread.currentThread().getName() + ":" + flag);
			flag = "A";
			super.notifyAll();
		} else {
			super.wait();
		}
	}
}